﻿using System.Net;
using System;
using System.Collections.Specialized;
using System.Net.Sockets;
namespace DataToViz
{
    public class IPV4Helper
    {
        public static string IPV4 = "";

        static IPV4Helper()
        {
            IPHostEntry ipEntry = Dns.GetHostEntry(Dns.GetHostName());
            string ip = ipEntry.AddressList[0].ToString();
            IPV4 = ip;
            ShowIP(out IPV4);
        }
        static void ShowIP(out string IPV4)
        {
            //ipv4地址也可能不止一个 
            IPV4 = "";
            string[] array = GetLocalIpv4();
            if (array.Length > 0)
            {
                foreach (string ip in array)
                {
                    //this.richTextBoxIPv4.AppendText(ip.ToString());
                    Console.WriteLine(ip + ",");
                    IPV4 = ip;
                }
            }
            else
            {
                IPV4 = "127.0.0.1";
            }
        }
        static string[] GetLocalIpv4()
        {
            //事先不知道ip的个数，数组长度未知，因此用StringCollection储存  
            IPAddress[] localIPs;
            localIPs = Dns.GetHostAddresses(Dns.GetHostName());
            StringCollection IpCollection = new StringCollection();
            foreach (IPAddress ip in localIPs)
            {
                //根据AddressFamily判断是否为ipv4,如果是InterNetWorkV6则为ipv6  
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                    IpCollection.Add(ip.ToString());
            }
            string[] IpArray = new string[IpCollection.Count];
            IpCollection.CopyTo(IpArray, 0);
            return IpArray;
        }
    }
}
